package com.ervanalb.cellradio.shared.communicator;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import com.ervanalb.cellradio.shared.communicator.packets.Packet;

/**
 * Implements a PacketListener which is backed by a queue. This is highly
 * recommended breaks the synchrony between the Communicator and the listening
 * class, freeing the Communicator to continue reception of packets while the
 * current ones are being processed.
 * 
 * When a packet arrives to this listener, it is placed on the queue. Another
 * thread may pop the queue to obtain packets, without fear of stalling the
 * Communicator.
 * 
 * @author eric
 */
public class QueuedListener implements PacketListener {
	protected BlockingQueue<Packet> queue;

	public QueuedListener() {
		queue = new LinkedBlockingQueue<Packet>();
	}

	@Override
	public void processPacket(Packet p) {
		try {
			queue.put(p);
		} catch (InterruptedException e) {
		}
	}

	public Packet pop(long timeout) {
		try {
			return queue.poll(timeout, TimeUnit.MILLISECONDS);
		} catch (InterruptedException e) {
			return null;
		}
	}
}
